// 公共方法
let plat = 'mp-weixin';
let lang = getApp().globalData.lang
import chatInterceptor from "@/common/chatInterceptor"

import TencentCloudChat from '@tencentcloud/chat';
import store from "@/store/index.js"
import {
	HTTP_REQUEST_URL,
	IMAGE_URL,
	IM_URL,
	PERFIX,
	kfs,
	LOCALE
} from "@/config/app"

import Vue from 'vue'
//国际化
import RU from '@/lang/ru-RU.json'
import CN from '@/lang/zh-CN.json'
import VueI18n from 'vue-i18n'
const messages = {
	'ru': RU,
	'zh': CN,
}
let i18nConfig = {
	locale: LOCALE, // 获取已设置的语言
	messages,
	silentTranslationWarn: true, // 去除国际化警告
}
Vue.use(VueI18n)
let i18n = new VueI18n(i18nConfig)
Vue.config.productionTip = false
Vue.prototype._i18n = i18n
let app2 = new Vue({
	i18n
})

//import app from '@/main'

// #ifdef APP-PLUS
import TUIChatEngine, {
	TUIStore,
	StoreName,
	TUIConversationService,
	TUIFriendService,
	TUIChatService
} from "@tencentcloud/chat-uikit-engine";
// #endif

// #ifdef WEB
import TUIChatEngine, {
	TUIStore,
	StoreName,
	TUIConversationService,
	TUIFriendService,
	TUIChatService
} from "@tencentcloud/chat-uikit-engine";
// #endif

export function platForm() {
	let plat_local = uni.getStorageSync('plat');
	if (plat_local) {
		plat = plat_local
	} else {
		uni.getSystemInfo({
			success: function(res) {
				if (res.uniPlatform === 'app') {
					plat = 'app'
				} else if (res.uniPlatform === 'web') {
					plat = 'web'
				} else if (res.uniPlatform === 'mp-weixin') {
					plat = 'mp-weixin'
				}
				uni.setStorage({
					key: 'plat',
					data: plat
				})
			}
		});
	}
}

/**
 * 判断是否授权并返回openid
 * @returns {any|boolean}
 */
export function getOpenid(vm) {
	platForm()
	if (plat === 'web') {
		return '';
	} else if (plat === 'app') {
		return '';
	} else {
		return new Promise(function(resolve, reject) {
			let mp_openid = uni.getStorageSync('mp_openid');
			if (mp_openid && mp_openid !== '') {
				resolve(mp_openid)
			} else {
				wechatMpAuth(vm).then(res => {
					mp_openid = res
					resolve(mp_openid)
				})
			}
		})
	}
}

/**
 * 小程序授权
 * @param vm uView实例
 */
function wechatMpAuth(vm) {
	return new Promise(function(resolve, reject) {
		uni.login({
			provider: 'weixin',
			success: function(loginRes) {
				// 获取openid
				vm.api.user.getOpenidByCode({
					code: loginRes.code
				}).then(res => {
					let mp_openid = res
					uni.setStorage({
						key: 'mp_openid',
						data: mp_openid
					})
					resolve(mp_openid)
				}).catch(err => {
					console.log(err);
				})
			}
		});
	})
}

//判断头像是否为base64
export const isBase64 = (str) => {
	if (!str) return
	let str1 = str;
	if (typeof str == 'object') {
		str1 = str['url']
	}
	return !!(str1.includes("data:image") && str1.includes(";base64,"));
}
//拼接前缀url
export const ImageUrl = (url) => {
	return isBase64(url) ? url : IMAGE_URL + url
}
//毫秒转时间(秒和毫秒）
export const time = (type = "MS", date1, str = "year") => {
	if (type === "S") date1 = date1 * 1000 //秒
	let year = new Date(date1).getFullYear();
	let month = (new Date(date1).getMonth() + 1) > 9 ? (new Date(date1).getMonth() + 1) : '0' + (new Date(date1)
		.getMonth() + 1);
	let date = new Date(date1).getDate() > 9 ? new Date(date1).getDate() : '0' + new Date(date1).getDate();
	let hours = new Date(date1).getHours() > 9 ? new Date(date1).getHours() : '0' + new Date(date1).getHours();
	let minutes = new Date(date1).getMinutes() > 9 ? new Date(date1).getMinutes() : '0' + new Date(date1)
		.getMinutes();
	let seconds = new Date(date1).getSeconds() > 9 ? new Date(date1).getSeconds() : '0' + new Date(date1)
		.getSeconds();
	if (str === "year") {
		return `${year}.${month}.${date} ${hours}:${minutes}:${seconds}`
	}
	if (str === "date") {
		return `${year + `-` + month + `-` + date}`
	}
	return `${year + str + month + str + date} ${hours}:${minutes}:${seconds}`
}
//判断是否为对象
export const isObject = (obj) => {
	return Object.prototype.toString.call(obj) === '[object Object]'
}
//用于组件cardReveal数据的处理
export const exitCard = (template = [], data = {}) => {
	if (getApp().globalData.lang == 'zh') {
		i18nConfig = {
			locale: 'zh', // 获取已设置的语言
			messages,
			silentTranslationWarn: true, // 去除国际化警告
		}
		Vue.use(VueI18n)
		i18n = new VueI18n(i18nConfig)
		Vue.config.productionTip = false
		Vue.prototype._i18n = i18n
		app2 = new Vue({
			i18n
		})
	} else {
		i18nConfig = {
			locale: 'ru', // 获取已设置的语言
			messages,
			silentTranslationWarn: true, // 去除国际化警告
		}
		Vue.use(VueI18n)
		i18n = new VueI18n(i18nConfig)
		Vue.config.productionTip = false
		Vue.prototype._i18n = i18n
		app2 = new Vue({
			i18n
		})
	}

	//判断传进来的模版是否为空
	if (template.length === 0 || !Array.isArray(template)) {
		return []
	}
	//判断是否为对象
	if (!isObject(data)) {
		return []
	}
	template.forEach((item, index) => {
		//根据key来找到对应的对象
		let arr = item.key.split('.')
		let obj = data;
		for (let i in arr) {

			if (['mergename'].indexOf(arr[i]) !== -1) {
				obj = obj[app2.$i18n.t("item.city." + arr[i])]
			} else if (['username', 'identity_name'].indexOf(arr[i]) !== -1) {
				obj = obj[app2.$i18n.t("item.user." + arr[i])]
			} else if (['title', 'con_text', 'name', 'content', 'desc', 'introduction', 'person_name',
					'goods_num', 'goods_weight', 'goods_volume', 'show_text', 'mode_value', 'company_name',
					'car_l', 'car_w', 'car_h', 'industry', 'skill', 'con', 'speed_ranking', 'price_ranking',
					'num_ranking'
				].indexOf(arr[i]) !== -1) {
				obj = obj[app2.$i18n.t("item." + arr[i])]
			} else {
				obj = obj[arr[i]]
			}
		}
		//判断是否为数组（数组一定为图片）
		if (Array.isArray(obj)) {
			obj.forEach(it => {
				template[index].images.push(ImageUrl(it.url))
			})
		} else {
			//判断是否为图片
			if (item.isIcon) {
				obj.split(',').forEach(immma => template[index].images.push(ImageUrl(immma)))
			}
			//处理时间戳
			if (item.isTimer) {
				template[index].message = time("S", obj) || app2.$i18n.t('')
			} else {
				template[index].message = obj || app2.$i18n.t('')
			}

		}

	})
	return template
}

export function goImTUIConversation(vm) {
	var mobile = uni.getStorageSync('mobile');

	if (getApp().globalData.lang == 'zh') {
		i18nConfig = {
			locale: 'zh', // 获取已设置的语言
			messages,
			silentTranslationWarn: true, // 去除国际化警告
		}
		Vue.use(VueI18n)
		i18n = new VueI18n(i18nConfig)
		Vue.config.productionTip = false
		Vue.prototype._i18n = i18n
		app2 = new Vue({
			i18n
		})
	} else {
		i18nConfig = {
			locale: 'ru', // 获取已设置的语言
			messages,
			silentTranslationWarn: true, // 去除国际化警告
		}
		Vue.use(VueI18n)
		i18n = new VueI18n(i18nConfig)
		Vue.config.productionTip = false
		Vue.prototype._i18n = i18n
		app2 = new Vue({
			i18n
		})
	}

	// 获取token
	if (!mobile) {
		vm.$u.toast(app2.$i18n.t('请先登录'));
		setTimeout(() => {
			// 此为uView的方法，详见路由相关文档
			vm.$u.route('/pages/user/login/login')
		}, 1000)
		return
	}
	// 跳转IM - webview
	vm.$u.route({
		url: "/pages/message/im/im",
		params: {
			type: "list",
			mobile: mobile
		}
	})
}




export async function createC2CConversation(to_mobile, vm, iskf = false) {
	// 即时聊天权限与业务控制
	const interceptorRes = await chatInterceptor(vm);
	if (!interceptorRes) return;
	var that = this
	var mobile = uni.getStorageSync('mobile');

	console.log('发送方的手机' + mobile, '接收者手机号' + to_mobile)
	if (getApp().globalData.lang == 'zh') {
		i18nConfig = {
			locale: 'zh', // 获取已设置的语言
			messages,
			silentTranslationWarn: true, // 去除国际化警告
		}
		Vue.use(VueI18n)
		i18n = new VueI18n(i18nConfig)
		Vue.config.productionTip = false
		Vue.prototype._i18n = i18n
		app2 = new Vue({
			i18n
		})
	} else {
		i18nConfig = {
			locale: 'ru', // 获取已设置的语言
			messages,
			silentTranslationWarn: true, // 去除国际化警告
		}
		Vue.use(VueI18n)
		i18n = new VueI18n(i18nConfig)
		Vue.config.productionTip = false
		Vue.prototype._i18n = i18n
		app2 = new Vue({
			i18n
		})
	}
	// 获取token
	if (!mobile) {
		vm.$u.toast(app2.$i18n.t('请先登录'));
		setTimeout(() => {
			// 此为uView的方法，详见路由相关文档
			vm.$u.route('/pages/user/login/login')
		}, 1000)
		return
	} else if (mobile == undefined) {
		vm.$u.toast(app2.$i18n.t('请先登录'));
		setTimeout(() => {
			// 此为uView的方法，详见路由相关文档
			vm.$u.route('/pages/user/login/login')
		}, 1000)
		return
	} else if (mobile == 'undefined') {
		vm.$u.toast(app2.$i18n.t('请先登录'));
		setTimeout(() => {
			// 此为uView的方法，详见路由相关文档
			vm.$u.route('/pages/user/login/login')
		}, 1000)
		return
	}



	if (mobile === to_mobile) {
		vm.$u.toast(app2.$i18n.t('不能与自己聊天'));
		return false
	}

	if ((to_mobile == 'undefined') || (to_mobile == undefined)) {
		to_mobile = 'customer001';
	}

	let isBothFriend = await isFriend({
		userID: PERFIX + to_mobile
	});


	// #ifdef APP-PLUS
	if (iskf) {
		var userID = kfs[0]
	} else {
		var userID = PERFIX + to_mobile
	}

	const conversationID = `C2C${userID}`;
	// uni.showModal({
	// 	title: app2.$i18n.t("该功能将获取以下权限"),
	// 	content: app2.$i18n.t("读取相册权限：以便您能够选择并上传图片或视频到我们的应用中") + "\n" +
	// 		app2.$i18n.t("摄像头权限：以便您能够选择并上传图片或视频到我们的应用中") + "\n" +
	// 		app2.$i18n.t("文件权限：以便您能够选择并上传文件到我们的应用中") + "\n" +
	// 		app2.$i18n.t("麦克风权限：当您使用聊天发送语音消息或音频聊天时,以便您能够发送语音到我们的应用中"),			
	// 	confirmText: app2.$i18n.t("同意"),
	// 	cancelText: app2.$i18n.t("算了"),
	// 	success(e) {
	// 		if (e.confirm) {
	uni.request({
		url: HTTP_REQUEST_URL + '/demo/message_score',
		data: {
			mobile: mobile
		},
		header: {},
		success: async (r) => {
			if (r.data.data) {

				TUIConversationService.getConversationProfile(conversationID)
					.then((res) => {
						if (!isBothFriend) {
							let obj = {
								to: userID,
								source: "AddSource_Type_Web",
							}
							addFriend(obj);
						}
						TUIConversationService.switchConversation(
							res.data.conversation.conversationID
						);
						uni.navigateTo({
							url: '/TUIKit/components/TUIChat/index'
						});
					})
					.catch((err) => {
						// uni.showToast({
						// 	title: "The other party has not registered for a chat service",
						// 	icon: 'none'
						// })
						uni.showModal({
							content: app2.$i18n.t('您的权限不足哦!请联系工作人员!'),
							showCancel: false,
							confirmText: app2.$i18n.t('是'),
						})
						console.warn("打开会话失败", err.code, err.msg);
						createC2CConversation('iaYt02jzhHmoCCCqGpaxf5G0VzuMPwLU', that, true)

					});
			} else {
				uni.showModal({
					content: app2.$i18n.t('您的权限不足哦!请联系工作人员!'),
					showCancel: false,
					confirmText: app2.$i18n.t('是'),
				})
				return false;
			}
		},
	})

	// 		}
	// 	}
	// })

	// #endif

	// #ifdef WEB
	if (iskf) {
		var userID = kfs[0]
	} else {
		var userID = PERFIX + to_mobile
	}

	const conversationID = `C2C${userID}`;
	TUIConversationService.getConversationProfile(conversationID)
		.then((res) => {
			TUIConversationService.switchConversation(
				res.data.conversation.conversationID
			);
			uni.request({
				url: HTTP_REQUEST_URL + '/demo/message_score',
				data: {
					mobile: mobile
				},
				header: {},
				success: (r) => {
					if (r.data.data) {
						if (!isBothFriend) {
							let obj = {
								to: userID,
								source: "AddSource_Type_Web",
							}
							addFriend(obj);
						}
						uni.navigateTo({
							url: '/TUIKit/components/TUIChat/index'
						});
					} else {
						uni.showModal({
							content: app2.$i18n.t('您的权限不足哦!请联系工作人员!'),
							showCancel: false,
							confirmText: app2.$i18n.t('是'),
						})
						return false;
					}
				},
			})

		})
		.catch((err) => {
			// uni.showToast({
			// 	title: "The other party has not registered for a chat service",
			// 	icon: 'none'
			// })
			uni.showModal({
				content: app2.$i18n.t('您的权限不足哦!请联系工作人员!'),
				showCancel: false,
				confirmText: app2.$i18n.t('是'),
			})
			console.warn("打开会话失败", err.code, err.msg);
			createC2CConversation('iaYt02jzhHmoCCCqGpaxf5G0VzuMPwLU', that, true)
		});
	// #endif

	// #ifdef MP
	// 跳转IM - webview
	// 聊天的userID
	if (to_mobile == 'customer002') {
		to_mobile == 'customer001';
	}
	uni.request({
		url: HTTP_REQUEST_URL + '/demo/message_score',
		data: {
			mobile: mobile
		},
		header: {},
		success: (r) => {
			if (r.data.data) {
				if (!isBothFriend) {
					let obj = {
						to: userID,
						source: "AddSource_Type_Web",
					}
					addFriend(obj);
				}
				vm.$u.route({
					url: "/TUIKit/components/TUIConversation/index",
					params: {
						iskf,
						to_mobile,
						type: 'detail'
					}
				})
			} else {
				uni.showModal({
					content: app2.$i18n.t('您的权限不足哦!请联系工作人员!'),
					showCancel: false,
					confirmText: app2.$i18n.t('是'),
				})
				return false;
			}
		},
	})
	// #endif

}

const isFriend = (info) => {
	return new Promise((resolve, reject) => {
		if (info?.groupID || !info?.userID) {
			resolve(false);
			return;
		}
		if (info?.addTime) {
			resolve(true);
			return;
		}
		TUIFriendService.checkFriend({
				userIDList: [info?.userID],
				type: TUIChatEngine.TYPES.SNS_CHECK_TYPE_BOTH,
			})
			.then((res) => {
				switch (res?.data?.successUserIDList[0]?.relation) {
					// 无好友关系：A 的好友表中没有 B，B 的好友表中也没有 A
					case TUIChatEngine.TYPES.SNS_TYPE_NO_RELATION:
						resolve(false);
						break;
						// 单项好友：A 的好友表中有 B，但 B 的好友表中没有 A
					case TUIChatEngine.TYPES.SNS_TYPE_A_WITH_B:
						resolve(false);
						break;
						// 单项好友：A 的好友表中没有 B，但 B 的好友表中有 A
					case TUIChatEngine.TYPES.SNS_TYPE_B_WITH_A:
						resolve(false);
						break;
						// 双向好友关系
					case TUIChatEngine.TYPES.SNS_TYPE_BOTH_WAY:
						resolve(true);
						break;
					default:
						resolve(false);
						break;
				}
			})
			.catch((error) => {
				console.warn("checkFriend error", error);
				reject(error);
			});
	});
};

const addFriend = (params) => {
	TUIFriendService.addFriend(params)
		.then((res) => {
			// Toast({
			// 	//message: TUITranslateService.t("TUIContact.申请已发送"),
			// 	message: 'SUCCESS',
			// 	type: TOAST_TYPE.SUCCESS,
			// });
		})
		.catch((error) => {
			console.warn("delete friend failed:", error);
		});
};

//实时获取胶囊位置
export function getCapsule() {
	return uni.getMenuButtonBoundingClientRect()
}




export const isVideo = (fileName) => {
	// 后缀获取
	let suffix = ''
	// 获取类型结果
	let result = false
	try {
		let flieArr = fileName.split('.')
		suffix = flieArr[flieArr.length - 1]
	} catch (err) {
		suffix = ''
	}
	// 图片格式
	let videoList = ['mp4', 'm2v', 'mkv', 'avi', 'rm', 'mpg', 'flv', 'rmvb'];
	// 进行图片匹配
	result = videoList.some(function(item) {
		return item === suffix
	})
	if (result) {
		result = true
		return result
	}
}

// 音频通话
export async function createVoiceCall(to_mobile, vm, iskf = false) {
	// const interceptorRes = await chatInterceptor(vm);
	// if (!interceptorRes) return;
	let mobile = uni.getStorageSync('mobile');

	if (getApp().globalData.lang == 'zh') {
		i18nConfig = {
			locale: 'zh', // 获取已设置的语言
			messages,
			silentTranslationWarn: true, // 去除国际化警告
		}
		Vue.use(VueI18n)
		i18n = new VueI18n(i18nConfig)
		Vue.config.productionTip = false
		Vue.prototype._i18n = i18n
		app2 = new Vue({
			i18n
		})
	} else {
		i18nConfig = {
			locale: 'ru', // 获取已设置的语言
			messages,
			silentTranslationWarn: true, // 去除国际化警告
		}
		Vue.use(VueI18n)
		i18n = new VueI18n(i18nConfig)
		Vue.config.productionTip = false
		Vue.prototype._i18n = i18n
		app2 = new Vue({
			i18n
		})
	}
	// 获取token
	if (!mobile) {
		vm.$u.toast(app2.$i18n.t('请先登录'));
		setTimeout(() => {
			// 此为uView的方法，详见路由相关文档
			vm.$u.route('/pages/user/login/login')
		}, 1000)
		return
	} else if (mobile == undefined) {
		vm.$u.toast(app2.$i18n.t('请先登录'));
		setTimeout(() => {
			// 此为uView的方法，详见路由相关文档
			vm.$u.route('/pages/user/login/login')
		}, 1000)
		return
	} else if (mobile == 'undefined') {
		vm.$u.toast(app2.$i18n.t('请先登录'));
		setTimeout(() => {
			// 此为uView的方法，详见路由相关文档
			vm.$u.route('/pages/user/login/login')
		}, 1000)
		return
	}



	if (mobile === to_mobile) {
		return false
	}
	if ((to_mobile == 'undefined') || (to_mobile == undefined)) {
		to_mobile = 'customer001';
	}


	// #ifdef APP-PLUS
	if (iskf) {
		var userID = kfs[0]
	} else {
		var userID = PERFIX + to_mobile
	}

	const conversationID = `C2C${userID}`;
	const options = {
		userID: userID,
		callMediaType: 1, // 语音通话(callMediaType = 1)、视频通话(callMediaType = 2)
	};
	// const chat1 = store.state.im.chat;
	// chat1.isReady();
	// try {
	// 	chat1.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, function(event) {
	// 		const actionType = JSON.parse(event.data[0].payload.data).actionType;
	// 		const cmd = JSON.parse(JSON.parse(event.data[0].payload.data).data).data.cmd;
	// 		const call_end = JSON.parse(JSON.parse(event.data[0].payload.data).data).call_end;
	// 		console.log("event.data[0]===============", JSON.parse(event.data[0]
	// 			.payload.data))
	// 		console.log("event.data[0].payload.data).data).data===============", JSON.parse(JSON.parse(event
	// 			.data[0].payload.data).data))
	// 		switch (actionType) {
	// 			case 1:
	// 				if (cmd === 'videoCall' || cmd === 'audioCall') console.log("发起通话");
	// 				if (cmd === 'hangup') console.log("通话已结束,通话时长:" + call_end);

	// 				break;
	// 			case 2:
	// 				console.log("取消通话")
	// 				break;
	// 			case 3:
	// 				console.log("已接听")
	// 				break;
	// 			case 4:
	// 				console.log("拒绝通话")
	// 				break;
	// 			case 5:
	// 				console.log("超时未接听")
	// 				break;
	// 			default:
	// 				break;
	// 		}
	// 		// 收到推送的单聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
	// 		// event.name - TencentCloudChat.EVENT.MESSAGE_RECEIVED
	// 		// event.data - 存储 Message 对象的数组 - [Message]
	// 	});
	// } catch (e) {
	// 	//TODO handle the exception
	// 	console.log("eeeeeee============", e)
	// }

	uni.$TUICallKit.call(options, (res) => {
		if (res.code === 0) {
			console.log('call success');
		} else {
			console.log(`call failed, error message = ${res.msg}`);
		}
	});
	// uni.$TUICallKit.call({
	// 		userID: userID,
	// 		callMediaType: 1,
	// 	},
	// 	(res) => {
	// 		if (res.code === 0) {
	// 			console.log('TUICallkit call success');
	// 		} else {
	// 			console.log(`TUICallkit call failed,${res.msg}`);
	// 		}
	// 	});

	// #endif

	// #ifdef WEB
	if (iskf) {
		var userID = kfs[0]
	} else {
		var userID = PERFIX + to_mobile
	}
	const options = {
		userID: userID,
		callMediaType: 1, // 语音通话(callMediaType = 1)、视频通话(callMediaType = 2)
	};
	uni.$TUICallKit.call({
			userID: userID,
			callMediaType: 1,
		},
		(res) => {
			if (res.code === 0) {
				console.log('TUICallkit call success');
			} else {
				console.log(`TUICallkit call failed,${res.msg}`);
			}
		});

	const conversationID = `C2C${userID}`;

	// #endif
}


// 申请视频通话
export async function createSendMessage(to_mobile, text, vm, iskf = false) {
	let mobile = uni.getStorageSync('mobile');

	if (getApp().globalData.lang == 'zh') {
		i18nConfig = {
			locale: 'zh', // 获取已设置的语言
			messages,
			silentTranslationWarn: true, // 去除国际化警告
		}
		Vue.use(VueI18n)
		i18n = new VueI18n(i18nConfig)
		Vue.config.productionTip = false
		Vue.prototype._i18n = i18n
		app2 = new Vue({
			i18n
		})
	} else {
		i18nConfig = {
			locale: 'ru', // 获取已设置的语言
			messages,
			silentTranslationWarn: true, // 去除国际化警告
		}
		Vue.use(VueI18n)
		i18n = new VueI18n(i18nConfig)
		Vue.config.productionTip = false
		Vue.prototype._i18n = i18n
		app2 = new Vue({
			i18n
		})
	}
	// 获取token
	if (!mobile) {
		vm.$u.toast(app2.$i18n.t('请先登录'));
		setTimeout(() => {
			// 此为uView的方法，详见路由相关文档
			vm.$u.route('/pages/user/login/login')
		}, 1000)
		return
	} else if (mobile == undefined) {
		vm.$u.toast(app2.$i18n.t('请先登录'));
		setTimeout(() => {
			// 此为uView的方法，详见路由相关文档
			vm.$u.route('/pages/user/login/login')
		}, 1000)
		return
	} else if (mobile == 'undefined') {
		vm.$u.toast(app2.$i18n.t('请先登录'));
		setTimeout(() => {
			// 此为uView的方法，详见路由相关文档
			vm.$u.route('/pages/user/login/login')
		}, 1000)
		return
	}



	if (mobile === to_mobile) {
		return false
	}
	if ((to_mobile == 'undefined') || (to_mobile == undefined)) {
		to_mobile = 'customer001';
	}

	if (iskf) {
		var userID = kfs[0]
	} else {
		var userID = PERFIX + to_mobile
	}

	const conversationID = `C2C${userID}`;

	let tranText = await textTranslation(text, mobile, userID)

	const options = {
		to: userID,
		conversationType: "C2C",
		payload: {},
		needReadReceipt: TUIStore.getData(StoreName.USER, "displayMessageReadReceipt") && TUIStore.getData(StoreName.APP, "enabledMessageReadReceipt"),
	};
	options.payload = {
		data: JSON.stringify({
			// 超文本类自定义消息标识字段
			businessID: "is_agree",
			// 文字描述
			text: tranText,
			// 超文本链接跳转 url
			link: "xxx"
		}),
		description: "",
		extension: ""
	};
	try {
		await TUIChatService?.sendCustomMessage(options);
	} catch (e) {
		console.log("e============", e)
	}


}

const textTranslation = async (text, from_userId, to_userId) => {
	// TODO::根据双方国籍，判断是否需要翻译
	console.log('新增翻译 = from---to---text', from_userId + '---' + to_userId + '---' + text)
	return new Promise((resolve, reject) => {

		var tranText = text;
		if (getApp().globalData.site.im_limit == 1) {
			let thstr = getApp().globalData.site.im_limit_text;
			let numList = extractNumbers(tranText);
			numList.map((item) => {
				if (isValidLength(tranText)) {
					tranText = tranText.replace(item, thstr);
				}
			})

			var im_limit_content = getApp().globalData.site.im_limit_content
			for (var i = 0; i < im_limit_content.length; i++) {
				if (tranText.indexOf(im_limit_content[i]) !== -1) {
					tranText = getApp().globalData.site.im_limit_text
					break;
				}
			}
		}
		text = tranText;

		uni.request({
			url: HTTP_REQUEST_URL + '/common/textTranslate',
			data: {
				from_mobile: from_userId,
				to_mobile: to_userId,
				text: text
			},
			header: {},
			success: (res) => {
				if (res.data.code !== 1) {
					resolve(text)
				}
				// let tranText = text + '（' + res.data.data.TargetText + '）'
				let tranText = res.data.data
				console.log('textTranslation-res', tranText)
				resolve(tranText)
			},
			fail: (err) => {
				reject(text)
			}
		})
	});
};